/*
 * @Description:  
 * @Autor: 商晓彬
 * @Date: 2021-07-20 11:26:35
 * @LastEditors: 商晓彬
 * @LastEditTime: 2022-01-04 14:37:40
 */
import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';
import { MessageService } from '@abp/message/message.service';
import { LazyLoadEvent } from 'primeng/api';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { AppSessionService } from '@shared/common/session/app-session.service';
import { WorkFlowServiceProxy, WorkFlowNodeDto, WorkNode, AffairRemindServiceProxy } from '@shared/service-proxies/service-proxies';
@Component({
    selector: 'app-process-configuration',
    templateUrl: './process-configuration.component.html',
    styleUrls: ['./process-configuration.component.less']
})
export class ProcessConfigurationComponent extends AppComponentBase {
    @ViewChild('typePaginator') typePaginator: Paginator;
    @ViewChild('typeData') typeData: Table;
    selected: any;// 左侧选择行数据
    nodeFlag = false;
    active = false;
    saveFlag = false;
    approvalForm = [];//审批流程图数据
    deatilForm = {
        label: undefined,
        choose: true,
        approvalRole: undefined,
        remark: undefined,
        roleName: undefined
    };
    approvalRoleOption = [
        {
            label: '请选择',
            value: undefined
        }
    ]
    msgIndex: any;
    cutFlag = true;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _user: AppSessionService,
        private _workFlowServiceProxy: WorkFlowServiceProxy,
        private _affairRemindServiceProxy: AffairRemindServiceProxy,
    ) {
        super(injector);
    }

    ngOnInit() {
        this._affairRemindServiceProxy.getAffairRoles()
            .pipe(finalize(() => { }))
            .subscribe(rs => {
                this.approvalRoleOption = [
                    {
                        label: '请选择',
                        value: undefined
                    }
                ]
                for (const item of rs.items) {
                    let data = { label: '', value: undefined };
                    data.label = item.displayName;
                    data.value = item.id;
                    this.approvalRoleOption.push(data);
                }
            });
    }
    getTypeTableList(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.typePaginator.changePage(0);
            return;
        }
        this._workFlowServiceProxy.getWorkFlowName(
            this.primengTableHelper.getSorting(this.typeData),
            this.primengTableHelper.getMaxResultCount(this.typePaginator, event),
            this.primengTableHelper.getSkipCount(this.typePaginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }
    searchMap(row) {
        this.approvalForm = [];
        this._workFlowServiceProxy.getWorkNodeById(
            row.id
        )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                let data = [];
                for (const item of result) {
                    let map = { label: '', approvalRole: undefined, remark: undefined, roleName: undefined };
                    map.label = item.wnName;
                    map.approvalRole = parseInt(item.handlers);
                    map.remark = item.nodeStatusDesc;
                    map.roleName = item.roleDesc;
                    data.push(map);
                }
                this.approvalForm = data;
            });
    }
    saveApproval() {
        if (this.approvalForm.length == 0) {
            this._messageService.warn("未维护审批流程");
            return;
        }
        for (const item of this.approvalForm) {
            if (item.roleName == undefined || item.roleName == '') {
                this._messageService.warn('未维护完审批角色');
                return;
            }

        }
        if (this.cutFlag) {
            this.cutFlag = false;
            for (let i = 0; i < this.approvalForm.length; i++) {
                let item = this.approvalForm[i];
                item.wfId = i + 2;
                if (i == this.approvalForm.length - 1) {
                    item.condition = [{ f: 1, n: 99 }, { f: 0, n: 100 }];
                    item.nextNode = 99 + ',100';
                } else {
                    item.condition = [{ f: 1, n: i + 3 }, { f: 0, n: 100 }];
                    item.nextNode = i + 3 + ',100';
                }

                if (i == 0) {
                    item.prevNode = 1;
                } else {
                    let data = this.approvalForm[i - 1];
                    item.prevNode = data.wfId;
                }
            }
            //保存审批流程
            let input = new WorkFlowNodeDto();
            input.wnID = this.selected.id;
            input.workNodes = [];
            let first = new WorkNode();
            first.wnID = this.selected.id;
            first.wfID = 1;
            first.wnName = '流程开始';
            first.prevNode = 0;
            let node = [{ f: 1, n: 1 }, { f: 0, n: 2 }];
            first.condition = JSON.stringify(node);
            first.nextNode = '1,2';
            first.nodeType = 1;
            first.nodeStatusDesc = '暂存';
            input.workNodes.push(first);
            //body
            for (const item of this.approvalForm) {
                let data = new WorkNode();
                data.condition = JSON.stringify(item.condition);
                data.nextNode = item.nextNode;
                data.handlers = item.approvalRole;
                data.nodeStatusDesc = item.remark;
                data.nodeType = 2;
                data.prevNode = item.prevNode;
                data.wfID = item.wfId;
                data.wnID = this.selected.id;
                data.wnName = item.label;
                input.workNodes.push(data);
            }
            //结束
            let lastSuccess = new WorkNode();
            lastSuccess.wnID = this.selected.id;
            lastSuccess.wfID = 99;
            lastSuccess.wnName = '完成';
            lastSuccess.prevNode = this.approvalForm[this.approvalForm.length - 1].wfId; //取数组Index
            lastSuccess.nextNode = '0';
            lastSuccess.nodeType = 3;
            lastSuccess.nodeStatusDesc = '结束';
            input.workNodes.push(lastSuccess);
            //未通过
            let lastFalse = new WorkNode();
            lastFalse.wnID = this.selected.id;
            lastFalse.wfID = 100;
            lastFalse.wnName = '未通过';
            lastFalse.prevNode = 0;
            lastFalse.nextNode = '0';
            lastFalse.nodeType = 3;
            lastFalse.nodeStatusDesc = '未通过';
            input.workNodes.push(lastFalse);
            this._workFlowServiceProxy.createWorkFlowNode(input)
                .pipe(finalize(() => { }))
                .subscribe((result) => {
                    if (result.code == 0) {
                        this.cutFlag = true;
                        if (result.code == 0) {
                            this._messageService.success('保存成功');
                            this.searchMap(this.selected);
                        } else {
                            this._messageService.error(result.message);
                        }
                    } else {
                        this._messageService.error(result.message)
                    }

                });
        }

    }
    addFirst(index?: any) {
        //添加流程图
        if (index >= 0) {
            this.approvalForm.splice(index + 1, 0, { choose: true, new: true });
        } else {
            this.approvalForm.unshift({ choose: true, new: true });
        }
    }
    deleteNode(index) {
        this.approvalForm.splice(index, 1);
    }
    showDetail(row, index) {

        setTimeout(() => {
            this.deatilForm = { ...row };
            this.deatilForm.choose = true;
            this.msgIndex = index;
            this.nodeFlag = true;
            this.active = true;
        }, 10);
    }
    onHide(event) {
        this.active = false;
        this.deatilForm.approvalRole = undefined;
        this.deatilForm.choose = true;
        this.deatilForm.label = undefined;
        this.deatilForm.remark = undefined;
    }
    save() {
        this.saveFlag = true;
        let that = this;
        for (const item of that.approvalRoleOption) {
            if (item.value == that.deatilForm.approvalRole) {
                that.deatilForm.roleName = item.label;
            }
        }
        this.approvalForm[this.msgIndex] = Object.assign({}, that.deatilForm);
        setTimeout(() => {
            this.nodeFlag = false;
        }, 10);

    }
}
